// 云函数入口文件
const cloud = require('wx-server-sdk')
var rp = require('request-promise');
const TcbRouter = require('tcb-router');
cloud.init({
	env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database({throwOnNotFound: false})
const _ = db.command
// 云函数入口函数
exports.main = async (event, context) => {
	const app = new TcbRouter({
		event
	})
	const {
		ENV,
		OPENID,
		APPID
	} = cloud.getWXContext()
	app.use(async (ctx, next) => {
		ctx.data = {}
		ctx.wxContext = cloud.getWXContext()
		await next()
	})
	/**
	 * showdoc
	 * @catalog 云开发·订单·新增订单
	 * @title 新增订单
	 * @description 新增订单
	 * @url order/editOrder 
	 */
	app.router('addOrder', async (ctx, next) => {
	    let hasDesk = await db.collection('desk_list').where({desk_id:event.order.desk_id}).get()
		if (!hasDesk.data.length) {
			ctx.body = {
				errCode: 400,
				errMsg: 'not found desk'
			};
		}
		let deskId = hasDesk.data[0]._id
		try {
			let updateResArr = [];
			let proResArr = [];
			let stockArr=[];
			const transaction = await db.startTransaction()
			for (let v of event.order.product_list) {
				const proRes = await db.collection('product_list').where({product_id:v.product_id,product_stock:_.gte(v.product_num)}).get()
				proResArr.push(proRes)
				if (proRes.data.length) {
					const updateRes = await transaction.collection('product_list')
						.doc(v._id).update({
							data: {
								product_stock: _.inc(-v.product_num)
							}
						})

					if (updateRes.stats.updated == 1) {
						updateResArr.push(updateRes)
					}else{
						stockArr.push(v)
					}
				}
			}
			let order = JSON.parse(JSON.stringify(event.order))
			const orderRes = await transaction.collection('order_list')
				.add({
					data: order
				})
			const deskRes = await transaction.collection('desk_list')
				.doc(deskId).update({
					data: {
						total_price:order.order_price,
						status:'order'
					}
				})	
			if (updateResArr.length != order.product_list
				.length || !orderRes._id || !deskRes.stats.updated) {
				await transaction.rollback()
				ctx.body = {
					errCode: 400,
					errMsg: '下单失败!',
					// data:{deskRes:deskRes,orderRes:orderRes,updateResArr:updateResArr,proResArr:proResArr,staus:'rollback'}
					data:{stockArr:stockArr}
				};
			}
			if (updateResArr.length == order.product_list
				.length && orderRes._id&&deskRes.stats.updated) {
				await transaction.commit()
				ctx.body = {
					errCode: 200,
					errMsg: '下单成功!',
					// data:{orderRes:orderRes,updateResArr:updateResArr,proResArr:proResArr,staus:'commit'}
				};
			}
		} catch (e) {
			ctx.body = {
				errCode: 400,
				errMsg: e.message,
				status:'catch'
			};
		}
	})
	/**
	 * showdoc
	 * @catalog 云开发·订单·更新订单
	 * @title 更新订单
	 * @description 更新订单
	 * @url order/editOrder 
	 */
	app.router('editOrder', async (ctx, next) => {
		let oldOrder = await db.collection('order_list').doc(event.order._id).get()
		if (!oldOrder.data) {
			ctx.body = {
				errCode: 400,
				errMsg: 'not found old'
			};
		}
		let hasDesk = await db.collection('desk_list').where({desk_id:event.order.desk_id}).get()
		if (!hasDesk.data.length) {
			ctx.body = {
				errCode: 400,
				errMsg: 'not found desk'
			};
		}
		let deskId = hasDesk.data[0]._id
		try {
			let updateResArr = [];
			let proResArr = [];
			let subArr = [];
			let stockArr = [];
			const transaction = await db.startTransaction()
			for (let v of event.order.product_list) {
				const proRes = await db.collection('product_list').where({product_id:v.product_id,product_stock:_.gte(v.product_num)}).get()
				proResArr.push(proRes)
				if (proRes.data.length) {
					if(!v.is_print){
						const updateRes = await transaction.collection('product_list')
							.doc(v._id).update({
								data: {
									product_stock: _.inc(-v.product_num)
								}
							})
						if (updateRes.stats.updated == 1) {
							updateResArr.push(updateRes)
						}else{
							stockArr.push(proRes)
						}
					}else{
						subArr.push(1)
					}
				}
			}
			let order = JSON.parse(JSON.stringify(event.order))
			order.create_time = Date.now()
			delete order._id
			delete order._openid
			const orderRes = await transaction.collection('order_list').doc(event.order._id)
				.update({
					data: order
				})
			const deskRes = await transaction.collection('desk_list')
				.doc(deskId).update({
					data: {
						create_time:Date.now(),
						total_price:order.order_price,
						status:'order'
					}
				})		
			if (updateResArr.length + subArr.length != order.product_list
				.length || !orderRes.stats.updated || !deskRes.stats.updated) {
				await transaction.rollback()
				let data
				if(stockArr.length){
					data = {
						errCode: 402,
						errMsg: '商品库存不足!',
						data:{stockArr:stockArr}, 
					}		
				}else{
					data = {
						errCode: 400,
						errMsg: '订单追加失败!',
						data:{deskRes:deskRes,subArr:subArr,'order_product_list':order.product_list,oldOrder:oldOrder.data.product_list,orderRes:orderRes,updateResArr:updateResArr,proResArr:proResArr,staus:'rollback'}
					};
				}
				ctx.body = data
			}
			if (updateResArr.length + subArr.length == order.product_list
				.length && orderRes.stats.updated && deskRes.stats.updated) {
				await transaction.commit()
				ctx.body = {
					errCode: 200,
					errMsg: '订单追加成功!',
					// data:{orderRes:orderRes,updateResArr:updateResArr,proResArr:proResArr,staus:'commit'}
				};
			}
		} catch (e) {
			ctx.body = {
				errCode: 400,
				errMsg: e.message
			};
		}
	})

	return app.serve();
}
